package com.qf.blog.web.controller;

import com.qf.blog.core.exception.JsonException;
import com.qf.blog.core.utils.R;
import com.qf.blog.web.entity.InvitataionEntity;
import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.service.ICommentService;
import com.qf.blog.web.service.IInvitataionService;
import com.qf.blog.web.service.IUserService;
import com.qf.blog.web.service.impl.LikeService;
import com.qf.blog.web.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/invitataionController")
public class InvitataionController {

    @Autowired
    private IInvitataionService invitataionService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private LikeService likeService;

    @PostMapping("/publish")
    @ResponseBody
    public R publish(@RequestBody InvitataionEntity invitataionEntity, HttpSession session) {
        // 1.获取登录用户
        UserEntity loginUser = (UserEntity) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new JsonException(100, "录超时，请先登录");
        }
        // 3.封装用户
        invitataionEntity.setUserId(loginUser.getId());
        boolean save = invitataionService.save(invitataionEntity);
        return R.out(save);
    }

    @GetMapping("/info/{id}")
    public String info(@PathVariable Integer id, Model model, HttpSession session) throws Exception {

        // 1.查询帖子信息
        InvitataionEntity invitataionEntity = invitataionService.getById(id);

        // 2.查询作者信息
        Integer userId = invitataionEntity.getUserId();
        UserEntity userEntity = userService.getById(userId);

        // 获取当前登录用户
        UserEntity loginUser = (UserEntity) session.getAttribute("loginUser");

        // 3.查询帖子的评论
        List<CommentVo> commentEntityList = commentService.commentListByInvitataionId(loginUser, invitataionEntity.getId());

        // 查看帖子的点赞数量
        Long count = likeService.getInvitataionLikeCount(1, id);


        Boolean likeStatus = false;
        if (loginUser != null) {
            // 查看登录用户是否对当前帖子点赞了
            likeStatus = likeService.getInvitataionUserLike(1, loginUser.getId(), id);
        }

        // 4.把帖子的数据和作者的数据放到map中
        model.addAttribute("topic", invitataionEntity);
        model.addAttribute("user", userEntity);
        model.addAttribute("commentVoList", commentEntityList);
        model.addAttribute("likeCount", count); // 帖子的点赞数量
        model.addAttribute("likeStatus", likeStatus ? 1 : 0); // 当前用户是否对这个帖子已经点过赞了

        // 5.跳转到视图
        return "view/site/discuss-detail";
    }
}
